# -*- coding: utf-8 -*-
STATUS_CODE_TEXT = {
    100: 'CONTINUE',
    101: 'SWITCHING PROTOCOLS',
    200: 'OK',
    201: 'CREATED',
    202: 'ACCEPTED',
    203: 'NON-AUTHORITATIVE INFORMATION',
    204: 'NO CONTENT',
    205: 'RESET CONTENT',
    206: 'PARTIAL CONTENT',
    300: 'MULTIPLE CHOICES',
    301: 'MOVED PERMANENTLY',
    302: 'FOUND',
    303: 'SEE OTHER',
    304: 'NOT MODIFIED',
    305: 'USE PROXY',
    306: 'RESERVED',
    307: 'TEMPORARY REDIRECT',
    400: 'BAD REQUEST',
    401: 'UNAUTHORIZED',
    402: 'PAYMENT REQUIRED',
    403: 'FORBIDDEN',
    404: 'NOT FOUND',
    405: 'METHOD NOT ALLOWED',
    406: 'NOT ACCEPTABLE',
    407: 'PROXY AUTHENTICATION REQUIRED',
    408: 'REQUEST TIMEOUT',
    409: 'CONFLICT',
    410: 'GONE',
    411: 'LENGTH REQUIRED',
    412: 'PRECONDITION FAILED',
    413: 'REQUEST ENTITY TOO LARGE',
    414: 'REQUEST-URI TOO LONG',
    415: 'UNSUPPORTED MEDIA TYPE',
    416: 'REQUESTED RANGE NOT SATISFIABLE',
    417: 'EXPECTATION FAILED',
    500: 'INTERNAL SERVER ERROR',
    501: 'NOT IMPLEMENTED',
    502: 'BAD GATEWAY',
    503: 'SERVICE UNAVAILABLE',
    504: 'GATEWAY TIMEOUT',
    505: 'HTTP VERSION NOT SUPPORTED',
}

from pycube.core.traceback import watcher
from pycube.core.sql import core_tables


import time,os

class system_initialize():    
    def __init__(self, config, environ, post, form, urls, adv_tpl = None):
        """        
        Starting the system.
        Sending needed headers to the WSGI, to force start        
        """
        self.config =config
        self.environ = environ
        self.status_code = 200      
        self.headers = []
        self.result_text = []
        self.post = post
        self.project_urls = urls
        
        self.native_form = form
        self.adv_tpl = adv_tpl
        
        
        self.headers.append( ('Content-type', 'text/html') )
        
        
        self.set_status_code(200)   
    
    
    def set_one_header(self, key, value):
        del( self.headers )
        self.headers = []
        self.set_header(key, value )
       
    
    def set_header(self, key, value):
        """
        Setting headers. 
        For example:
            cookies, redirecting and other.
        """
        self.headers.append( (key, str( value ) ) )       
    
    def remove_heades(self):
        self.headers = [ ('Content-type', 'text/html') ]

    def get_headers(self):
        """
        Returns the complete storage of headers        
        """
        return self.headers    
    
    def set_status_code(self, code):
        
        """        
        Setting Status code, to tell WSGI what happened        
        """
        
        if code not in STATUS_CODE_TEXT:
            raise Exception('Not valid. System halted')
        else:            
            self.status_code = code        
    
    def get_status_code(self):
        """
        This function returns special formed status for WSGI
        """
        return str(self.status_code) + ' ' + STATUS_CODE_TEXT[self.status_code]    
    
    def echo(self, text):
        """
        Writing to page content       
        
        import time
        system.echo(time.time())  
        
        """
        if text:
            self.result_text.append( str(text) )
            return True
        else:
            return False
        
    def response(self):
        """
        Returns result to WSGI, collecting all
        appended to list values, joining them with empty string
        """
        if len(self.result_text) > 0:
            return ''.join(self.result_text)
        else:
            return ''
        
        
    def start_the_world(self):
        watch = watcher(self.environ)
        start_system_time = time.time()
        try:
                  
            from pycube.core.urls import url_parser
            from pycube.core.urls import request
            from pycube.core.cookie import manage_cookie  
            from pycube.core.sessions import sess   
            #from pycube.core.sessions_global import sess            
                 
            from pycube.core.template import engine
            
            from pycube.core.sql.object import Psql
            psql = Psql( self.config, debug = True )
            
            if self.config.DEBUG:
                self.install_core_tables(psql, self.environ['REQUEST_URI'])
                
            
            
            
            
            cookie = manage_cookie( self.environ )            
            session = sess( self.environ, cookie, psql, self.echo  )            
            
            
            
            
                          
            iSessionData = session.start()        
            
            
            
            '''
            Setup Request object
            '''
            httpRequest = request.url_request(                            
                            self.environ, 
                            cookie, 
                            iSessionData,
                            self.echo,
                            self.set_header,
                            self.set_status_code,
                            self.post,                                                       
                            psql,
                            self.native_form,
                            self.config                
                         )
            
            
            urlib = url_parser( httpRequest, self.set_one_header, self.set_status_code, self.remove_heades,  engine.template, self.adv_tpl )                      
            urlib.parser( self.project_urls )           
            
            
            '''
            Setting cookie if they were set :)
            '''
            self.__cookie_work(cookie.get_cookie_request())
        
            
             
            
            
            self.echo( urlib.response() )            
        except:
            self.echo( watch.catch_error() )
    
    
    def install_core_tables(self, sql, url):        
        if url == '/install_core':
            core_tables.core_setup(sql)
            
    
    def __cookie_work( self, cookie_list ):        
        for cookie_header, cookie_values in cookie_list:
            self.set_header( cookie_header, cookie_values )
        
        
        
        
            
            
       
        
        
        
    
    
    
    
    
        
